import React, { useState } from 'react';
import { Form, Input, DatePicker, Button, Space, Card, message } from 'antd';
import { SearchOutlined } from '@ant-design/icons';
import { useDispatch } from 'react-redux';
import { searchFlights, fetchFlights } from '../../store/slices/flightSlice';

const FlightSearch = () => {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const dispatch = useDispatch();

  const handleSearch = async (values) => {
    setLoading(true);
    try {
      await dispatch(searchFlights({
        departure_city: values.departure_city,
        arrival_city: values.arrival_city,
        departure_date: values.departure_date?.format('YYYY-MM-DD'),
      })).unwrap();
      message.success('航班搜索完成');
    } catch (error) {
      message.error('搜索航班失败: ' + error.message);
    } finally {
      setLoading(false);
    }
  };

  const handleReset = () => {
    form.resetFields();
    dispatch(fetchFlights());
    message.info('已重置搜索条件');
  };

  return (
    <Card title="搜索航班" style={{ marginBottom: 16 }}>
      <Form
        form={form}
        layout="inline"
        onFinish={handleSearch}
        style={{ display: 'flex', gap: 16, flexWrap: 'wrap' }}
      >
        <Form.Item
          name="departure_city"
          label="出发城市"
          rules={[{ required: true, message: '请输入出发城市' }]}
        >
          <Input placeholder="请输入出发城市" style={{ width: 150 }} />
        </Form.Item>

        <Form.Item
          name="arrival_city"
          label="到达城市"
          rules={[{ required: true, message: '请输入到达城市' }]}
        >
          <Input placeholder="请输入到达城市" style={{ width: 150 }} />
        </Form.Item>

        <Form.Item
          name="departure_date"
          label="出发日期"
          rules={[{ required: true, message: '请选择出发日期' }]}
        >
          <DatePicker 
            placeholder="选择日期" 
            style={{ width: 150 }}
            format="YYYY-MM-DD"
          />
        </Form.Item>

        <Form.Item>
          <Space>
            <Button
              type="primary"
              htmlType="submit"
              icon={<SearchOutlined />}
              loading={loading}
            >
              搜索
            </Button>
            <Button onClick={handleReset}>
              重置
            </Button>
          </Space>
        </Form.Item>
      </Form>
    </Card>
  );
};

export default FlightSearch;